﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using Application = System.Windows.Application;
using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;

namespace RadarMonitorDeamon
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static NotifyIcon trayIcon;
        private static System.Threading.Mutex mutex;
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            mutex = new System.Threading.Mutex(true, "RadarMonitorDeamon_Only");
            if (!mutex.WaitOne(0, false))
            {
                this.Shutdown();
            }
            AddTrayIcon();

            var timer = new Timer();
            timer.Interval = 3000;
            timer.Tick += Timer_Tick;
            timer.Enabled = true;
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            RemoveTrayIcon();
            try
            {
                mutex.ReleaseMutex();
            }
            catch { }
            Environment.Exit(0);
        }

        private void RemoveTrayIcon()
        {
            if (trayIcon != null)
            {
                trayIcon.Visible = false;
                trayIcon.Dispose();
                trayIcon = null;
            }
        }

        private void AddTrayIcon()
        {
            try
            {
                if (trayIcon != null)
                {
                    return;
                }
                System.IO.Stream iconStream = GetResourceStream(new Uri("pack://application:,,,/radar-line.ico")).Stream;
                trayIcon = new NotifyIcon
                {
                    Icon = new System.Drawing.Icon(iconStream),
                    Text = "RadarMonitor守护线程"
                };
                trayIcon.Visible = true;

                ContextMenu menu = new ContextMenu();

                MenuItem closeItem = new MenuItem();
                closeItem.Text = "退出";
                closeItem.Click += new EventHandler(delegate { this.Shutdown(); });

                menu.MenuItems.Add(closeItem);

                trayIcon.ContextMenu = menu;    //设置NotifyIcon的右键弹出菜单
            }
            catch (Exception)
            { }

        }

        private bool alive = false;
        private void Timer_Tick(object sender, EventArgs e)
        {
            bool MonitorisAlive = true;
            try
            {
                var monitorMutex = System.Threading.Mutex.OpenExisting("RADMonitor_OnlyOneProcess");
                MonitorisAlive = !monitorMutex.WaitOne(0, false);
                if (!MonitorisAlive)//
                {
                    try { monitorMutex.ReleaseMutex(); } catch { }
                }
            }
            catch (System.Threading.WaitHandleCannotBeOpenedException)
            {
                Console.WriteLine("Mutex does not exist.");
                MonitorisAlive = false;
            }
            catch (System.Threading.AbandonedMutexException)
            {
                //  退出没有释放锁
                MonitorisAlive = false;
            }
            catch (Exception)
            { }
            
            if (!MonitorisAlive && alive)
            {
                // 发送钉钉通知
                alarm();
            }
            alive = MonitorisAlive;
        }

        private void alarm()
        {
            try
            {
               var webhook="https://oapi.dingtalk.com/robot/send?access_token=36a21bf65e25d148a8f4d78126e8aaae0c279c5741f82cd942367061682975c3";

                IDingTalkClient client = new DefaultDingTalkClient(webhook);
                OapiRobotSendRequest req = new OapiRobotSendRequest();
                req.Msgtype = "markdown";
                
                var str = "{\"title\":\"监控报警\", \"text\":\"";
                str += "RadarMonitor 已退出";
                str += "\"}";
                //var str = string.Format("{\"title\":\"监控报警\", \"text\":\"{0}\"}", content);
                req.Markdown = str;
                try
                {
                    OapiRobotSendResponse response = client.Execute(req);
                    Console.WriteLine($@"返回结果{response.Errcode}:{response.ErrMsg}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }

            }
            catch { }
        }
    }
}
